import React, { useState } from 'react';
import { ProFormUploadButton } from '@ant-design/pro-components';
import type { UploadRequestOption } from 'rc-upload/lib/interface';
import axios from 'axios';
import { message,UploadFile } from 'antd';
import { useIntl } from 'umi';

interface UploadButtonProps {
  name: string;
  label: string;
  action?: string;
  max?: number;
  accept?: string;
  bizType?: string;
  form?: any;
  initialValue?: string;
}

const UploadButton: React.FC<UploadButtonProps> = ({
  name,
  label,
  action = '/admin-api/infra/file/upload',
  max = 1,
  accept = 'image/*',
  bizType = 'cutomerLogo',
  form,
  initialValue,
}) => {
  const intl = useIntl();
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  // 初始化上传文件列表
  React.useEffect(() => {
    if (initialValue) {
      const uploadedFile: UploadFile = {
        uid: String(Date.now()),
        name: 'logo',
        status: 'done',
        url: initialValue,
      };
      setFileList([uploadedFile]);
    }
  }, [initialValue]);

  const customUpload = async (options: UploadRequestOption) => {
    const { file, onSuccess, onError, onProgress } = options;

    const formData = new FormData();
    formData.append('file', file as Blob);
    formData.append('bizType', bizType);

    try {
      const response = await axios.post(action, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: ({ total, loaded }) => {
          if (total) {
            const percent = Math.round((loaded / total) * 100);
            onProgress?.({ percent });
          }
        },
      });

      if (response.data.code != 0) {
        if (!response.data.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.operating" }));
        } else {
          message.error(response.data.msg);
          return false;
        }
      }

      const uploadedUrl = response.data.data;
      const uploadedFile: UploadFile = {
        uid: String(Date.now()),
        name: (file as any).name,
        status: 'done',
        url: uploadedUrl,
      };

      setFileList([uploadedFile]);
      form?.setFieldsValue({ [name]: uploadedUrl });

      onSuccess?.(uploadedUrl, file as any);
    } catch (err) {
      onError?.(err as any);
      message.error(intl.formatMessage({ 
        id: 'request.upload.failed',
        defaultMessage: "Upload failed" 
      }));
    }
  };
const handleChange = ({ fileList: newList }: { fileList: UploadFile[] }) => {
    const validFiles = newList.filter(file => file.status === 'done' && file.url);
    setFileList(validFiles);
    
    // 只提取URL设置到表单字段
    const urls = validFiles.map(file => file.url).filter(Boolean);
    form?.setFieldsValue({ 
      [name]: max === 1 ? urls[0] || null : urls 
    });
  };
  return (
    <ProFormUploadButton
      name={name}
      label={label}
      max={max}
      fieldProps={{
        accept,
        listType: 'picture-card',
        customRequest: customUpload,
        fileList,
       onChange: handleChange,
        showUploadList: {
          showPreviewIcon: true,
          showDownloadIcon: true,
        },
        onPreview: file => {
          if (file.url) {
            window.open(file.url, '_blank');
          }
        },
      }}
    />
  );
};

export default UploadButton;